package com.lzj.servlet;

import com.lzj.dao.UserDao;
import com.lzj.dao.impl.UserDaoImpl;
import com.lzj.entity.Order;
import com.lzj.entity.OrderData;
import com.lzj.entity.ShoppCart;
import com.lzj.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *
 * </p>
 *
 * @autor:lzj
 * @date:2021/12/13
 */
public class AddOrderServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int userId = (int)req.getSession().getAttribute("userId");
        UserServiceImpl userService = new UserServiceImpl();
        UserDao userDao = new UserDaoImpl();
        userService.setUserDao(userDao);
        Date date=new Date();
        List<ShoppCart> shoppCarts = userService.queryShoppCart(userId);
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Order order=new Order(date,false,userId);

        userService.addOrder(order);
        List<Order> orders = userService.queryOrder(userId);

        System.out.println(userId);
        System.out.println(orders);
        System.out.println(shoppCarts);

        int orderId=-1;
        for (Order order1 : orders) {//查找该用户新创建的订单号
            orderId=order1.getId();
        }

        for (ShoppCart shoppCart : shoppCarts) {
            OrderData orderData = new OrderData(shoppCart.getUrl(),shoppCart.getName(),shoppCart.getPrice(),shoppCart.getSpecification(),shoppCart.getCount(),shoppCart.getTotalPrice(),orderId,userId);
            userService.addOrderData(orderData);//添加订单中的数据
            userService.deleteShoppCart(shoppCart.getSkuId(),userId);//删除购物车中的商品
        }

        //购物车
        List<ShoppCart> shoppCarts1 = userService.queryShoppCart(userId);
        req.getSession().setAttribute("shoppCarts",shoppCarts1);
        //订单
        List<Order> orders1 = userService.queryOrder(userId);
        req.getSession().setAttribute("orders",orders1);
        //订单数据
        List<OrderData> orderData1 = userService.queryOrderData(userId);
        req.getSession().setAttribute("orderData",orderData1);

        resp.sendRedirect("user_center_order.jsp");

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
